package com.gzjh_group.photoalbum;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.target.Target;
import com.bumptech.glide.request.transition.Transition;
import com.zhy.http.okhttp.OkHttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;

import static com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade;

public class PhotoActivity extends AppCompatActivity {

    @BindView(R.id.viewPager)
    ViewPager viewPager;

    GirlImage girlImage = null;
    String url = "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/10/1";
    int imageCount = 0;
    int currentImage = 1;

    @BindView(R.id.tvImageShow)
    TextView tvImageShow;

    @OnClick({R.id.btnSave})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.btnSave:
                savePicture();
                break;
        }
    }

    private void savePicture() {
        String url = girlImage.getResults().get(currentImage-1).getUrl();
        GlideApp.with(this).asBitmap().load(url).into(new SimpleTarget<Bitmap>() {

            @Override
            public void onResourceReady(@NonNull final Bitmap bitmap, @Nullable Transition<? super Bitmap> transition) {
                if(saveImageToGallery(PhotoActivity.this, bitmap)){
                    ToastUtil.showSingleToast(PhotoActivity.this, "保存成功！");
                }else{
                    ToastUtil.showSingleToast(PhotoActivity.this, "保存失败！");
                }
            }

        });
    }

    //保存文件到指定路径
    public static boolean saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + context.getResources().getString(R.string.app_name);
        File appDir = new File(storePath);
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            //通过io流的方式来压缩保存图片
            boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            fos.flush();
            fos.close();

            //把文件插入到系统图库
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);

            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
            if (isSuccess) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo);
        ButterKnife.bind(this);

        OkHttpUtils.get().url(url).build().execute(new HttpCallBack<GirlImage>() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                if (!NetworkUtils.isWifiAvailable()){
                    ToastUtils.showLong("请检查网络连接！");
                }
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);

            }

            @Override
            public void onFailure(Call call, Exception e, int id) {

            }

            @Override
            public void onSuccess(final GirlImage response, int id) {
                girlImage = response;
                PhotoPagerAdapter photoPagerAdapter = new PhotoPagerAdapter(response, PhotoActivity.this);
                photoPagerAdapter.setImageLoader(new PhotoPagerAdapter.ImageLoader() {
                    @Override
                    public void loadImage(String url, final ImageView imageView) {
                        GlideApp.with(PhotoActivity.this).load(url).centerCrop().transition(withCrossFade()).listener(new RequestListener<Drawable>() {
                            @Override
                            public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                                imageView.setVisibility(View.INVISIBLE);
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                                imageView.setVisibility(View.VISIBLE);
                                return false;
                            }
                        }).into(imageView);
                    }
                });

                photoPagerAdapter.setOnPhotoTapListener(new PhotoPagerAdapter.OnPhotoTapListener() {
                    @Override
                    public void onPhotoTap(View view, float x, float y) {
                        finish();
                    }
                });
                photoPagerAdapter.setOnLongClickListener(new PhotoPagerAdapter.OnLongClickListener() {
                    @Override
                    public void onLongClick(View view, int position) {
                        Toast.makeText(PhotoActivity.this, "您点击了第 " + (position + 1) + " 张图片", Toast.LENGTH_SHORT).show();
                    }
                });
                viewPager.setAdapter(photoPagerAdapter);
                imageCount = response.getResults().size();
                tvImageShow.setText(imageCount + " / " + currentImage);
                viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                    @Override
                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                    }

                    @Override
                    public void onPageSelected(int position) {
                        currentImage = (position + 1);
                        tvImageShow.setText(imageCount + " / " + currentImage);
                    }

                    @Override
                    public void onPageScrollStateChanged(int state) {

                    }
                });
            }

        });

    }

}
